import {
  initSaveActiveTreeAssignOrganization,
  pageCuesActive,
} from '@/services/api/api-cues-active';
import { listCuesIndustry } from '@/services/api/api-cues-industry';
import { searchTreeOrganization } from '@/services/api/api-cues-submit';
import { findTagColor } from '@/utils/findTagColor';
import { FileImageOutlined, PaperClipOutlined } from '@ant-design/icons';
import {
  LightFilter,
  PageContainer,
  ProColumns,
  ProFormDateRangePicker,
  ProTable,
} from '@ant-design/pro-components';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import { ActionType } from '@ant-design/pro-table';
import { Badge, Card, Space, Tag } from 'antd';
import Meta from 'antd/es/card/Meta';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import 'dayjs/locale/zh-cn';
import moment from 'moment';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';
import TableSubmit from '../../topic/submit/TableSubmit';
import DetailsActive from './DetailsActive';
import EditActive from './EditActive';
interface SubmitPoolProps {
  onRefurbish: () => void;
}

const SubmitPool: React.FC<SubmitPoolProps> = ({ onRefurbish }) => {
  const access = useAccess();
  const [width, setWidth] = useState(500);
  const actionRef = useRef<ActionType>();

  const formRef = useRef<ProFormInstance>();

  const [industrys, setIndustrysState] = useState<any[]>([]);

  const [openAddActive, setOpenAddActive] = useState<boolean>(false);

  const [tabActiveKey, setTabActiveKeyState] = useState<string>('TableSubmitTopic');

  /**
   * 推送单位数据
   */
  const [treeAssignOrganizationData, setTreeAssignOrganizationDataState] = useState<DataNode[]>();

  const [articleOrganizations, setArticleOrganizationState] = useState<any[]>([]);

  /**
   * 搜索参数
   */
  const [queryParam, setQueryParamState] = useState({});

  const renderBadge = (count: number, active = false) => {
    return (
      <Badge
        count={count}
        style={{
          marginBlockStart: -2,
          marginInlineStart: 4,
          color: active ? '#1890FF' : '#999',
          backgroundColor: active ? '#E6F7FF' : '#eee',
        }}
      />
    );
  };
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  /**
   * 加载 单位 列表
   * @param key
   */
  const treeOrganizationData = async () => {
    try {
      const response = await searchTreeOrganization();
      if (response.code === 0) {
        setArticleOrganizationState(response.data);
      }
    } catch (error) {}
  };

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined  ,        children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 保存 推送 单位
   */
  const loadInitSaveActiveTreeAssignOrganization = async () => {
    try {
      const response = await initSaveActiveTreeAssignOrganization();
      if (response.code === 0) {
        setTreeAssignOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };

  /**
   * 加载权限详情
   * @param key
   */
  const getCuesIndustryData = async () => {
    try {
      const response = await listCuesIndustry();

      setIndustrysState(
        response.data.map((item) => {
          return { label: item.name, value: item.id };
        }),
      );
    } catch (error) {}
  };

  const columns: ProColumns<CuesActiveData.ActivePage>[] = [
    {
      title: '报送线索',
      dataIndex: 'articleName',
      // copyable: true,
      search: false,
      ellipsis: true,
      width: '300px',
      align: 'center',
      key: 'articleName',
      render: (dom, record, _index, action) => {
        return (
          <div
            style={{
              textAlign: 'left',
              textOverflow: 'ellipsis',
              whiteSpace: 'nowrap',
              overflow: 'hidden',
            }}
          >
            {record.isImage === 1 ? <FileImageOutlined /> : <></>}
            {record.isFile === 1 ? <PaperClipOutlined /> : <></>}
            <DetailsActive
              id={record.id}
              name={record.articleName}
              onRefurbish={() => {
                actionRef?.current?.reload();
              }}
            />
          </div>
        );
      },
    },
    {
      title: '选题方向',
      dataIndex: 'articleIndustryName',
      key: 'articleIndustryName',
      width: '80px',
      align: 'center',
      search: false,
      render: (_, row) => {
        let industrys = row?.articleIndustrys;

        if (industrys.length > 2) {
          industrys = industrys.slice(0, 2);
          industrys.push({
            label: '...',
            value: '...',
          });
        }

        return (
          <Space size={[0, 8]} wrap>
            {industrys?.map(
              (item) =>
                // <Tag key={item.value}>{item.label}</Tag>
                item.label,
            )}
          </Space>
        );
      },
    },
    {
      title: '单位',
      key: 'articleOrganizationAvatar',
      dataIndex: 'articleOrganizationAvatar',
      width: '180px',
      align: 'center',
      search: false,
      valueType: 'avatar',
      render: (dom, row) => (
        <div
          style={{
            textAlign: 'left',
            marginLeft: '24px',
          }}
        >
          <Tag color={findTagColor(row.articleOrganizationTopName)}>
            {row.articleOrganizationTopName}
          </Tag>
          <span>{dom}</span>
          {row.articleOrganizationName}
        </div>
      ),
    },

    // {
    //     title: '标签',
    //     dataIndex: 'articleLabels',
    //     key: 'articleLabels',
    //     width: '200px',
    //     align: 'center',
    //     search: false,
    //     render: (_, row) => {
    //         let labels = row?.articleLabels;

    //         if (labels.length > 2) {
    //             labels = labels.slice(0, 2);
    //             labels.push({
    //                 label: '...',
    //                 value: '...',
    //             });
    //         }
    //         return (
    //             <Space size={[0, 8]} wrap>
    //                 {labels?.map((item) => (
    //                     <Tag key={item.value}>{item.label}</Tag>
    //                 ))}
    //             </Space>
    //         );
    //     },
    // },
    {
      title: '新闻联络人',
      dataIndex: 'articleAccountName',
      // copyable: true,
      ellipsis: true,
      search: false,
      width: '100px',
      align: 'center',
      key: 'articleAccountName',
    },

    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: '120px',
      align: 'center',
      search: false,
    },
    {
      title: '报送日期',
      dataIndex: 'createdTimes',
      key: 'createdTimes',
      valueType: 'dateRange',
      hideInTable: true,
      fieldProps: {
        allowClear: true,
        placeholder: ['开始日期', '结束日期'],
        format: 'YYYY-MM-DD',
        ranges: {
          今日: [moment(), moment()],
          本月: [moment().startOf('month'), moment().endOf('month')],
          上月: [
            moment().startOf('month').subtract(1, 'months'),
            moment().endOf('month').subtract(1, 'months'),
          ],
          最近7天: [moment().subtract(6, 'days'), moment()],
          最近60天: [moment().subtract(59, 'days'), moment()],
          最近90天: [moment().subtract(89, 'days'), moment()],
        },
      },
    },
    {
      title: '操作',
      key: 'option',
      width: 50,
      valueType: 'option',
      render: (dom, record, _index, action) => {
        return (
          <EditActive
            id={record.id}
            onRefurbish={() => {
              onRefurbish();
              actionRef.current?.reload();
            }}
          />
        );
      },
    },
  ];
  return (
    <DrawerForm
      key="drawer_form_add_submit"
      title="线索池"
      drawerProps={{
        maskClosable: false,
        destroyOnClose: true,
        width: 1390,
      }}
      formRef={formRef}
      trigger={
        // <Button key="button_add_submit" type="primary">
        //   <PlusOutlined />
        //   报送线索
        // </Button>
        <Card
          hoverable
          bordered={false}
          style={{ width: 130, marginTop: 10, backgroundColor: '#b7eb8f' }}

          // cover={<img alt="example" src={cuesImage} />}
        >
          <Meta title="线索池选用" />
        </Card>
      }
      initialValues={{}}
      open={openAddActive}
      onOpenChange={(visible) => {
        setOpenAddActive(visible);
        if (visible) {
          getCuesIndustryData();
          loadInitSaveActiveTreeAssignOrganization();
        } else {
          setTreeAssignOrganizationDataState([]);
        }
      }}
      layout="horizontal"
    >
      <PageContainer
        header={{
          title: false,
          breadcrumb: {
            items: [],
          },
          style: {
            paddingBlockEnd: 0,
          },
        }}
        tabProps={{
          style: {
            margin: 0,
          },
          tabBarGutter: 30,
        }}
        tabList={[
          {
            tab: <span>选题线索{renderBadge(0, tabActiveKey === 'TableSubmitTopic')}</span>,
            key: 'TableSubmitTopic',
          },
          {
            tab: <span>主动报送{renderBadge(0, tabActiveKey === 'TableSubmitActive')}</span>,
            key: 'TableSubmitActive',
          },
        ]}
        tabActiveKey={tabActiveKey}
        onTabChange={setTabActiveKeyState}
      >
        {tabActiveKey === 'TableSubmitActive' ? (
          <ProTable<CuesActiveData.ActivePage>
            columns={columns}
            actionRef={actionRef}
            request={async (params = {}) => {
              if (params.organizationIds) {
                const organizationParentIds: string[] = [];
                let organizationIds: string[] = [];

                params.organizationIds.forEach((item: string | any[]) => {
                  if (item.length === 1) {
                    organizationParentIds.push(item[0]);
                  } else if (item.length > 1) {
                    organizationIds.push(item[1]);
                  }
                });
                organizationParentIds.forEach((id) => {
                  const ids = articleOrganizations.find((item) => item.id === id).children;
                  organizationIds = organizationIds.concat(ids.map((item: any) => item.id));
                });
                params.articleOrganizationIds = organizationIds;
              }

              const response = await pageCuesActive({
                createdSource: 1,
                ...queryParam,
                ...params,
              });
              return Promise.resolve({
                data: response.data.data,
                total: response.data.total,
                success: response.code === 0,
              });
            }}
            rowKey="id"
            dateFormatter="string"
            bordered
            search={false}
            sticky
            ghost
            pagination={{
              showQuickJumper: true,
              showSizeChanger: true,
              defaultPageSize: 20,
            }}
            options={false}
            toolbar={{
              filter: (
                <LightFilter
                  onValuesChange={(value) => {
                    setQueryParamState({ ...queryParam, ...value });
                    actionRef?.current?.reset();
                  }}
                >
                  {/* <ProFormCascader
                                     name="assignOrganizationIds"
                                     label="选择单位"
                                     allowClear
                                     width="xs"
                                     fieldProps={{
                                         placeholder:"选择单位",
                                         options: articleOrganizations,
                                         showSearch: { filter },
                                         multiple: true,
                                         removeIcon: true,
                                         allowClear: true,
                                         maxTagCount: 'responsive',
                                         showCheckedStrategy: Cascader.SHOW_CHILD,
                                         // onChange(value, selectOptions) {
                                         //     setQueryParamState({ ...queryParam, articleOrganizationIds: value });
                                         //     actionRef.current?.reset();
                                         // },
                                     }}
                                 /> */}
                  <ProFormDateRangePicker
                    name="createdTimes"
                    label="创建日期"
                    allowClear
                    width="sm"
                    fieldProps={{
                      allowClear: true,
                      placeholder: ['开始日期', '结束日期'],
                      format: 'YYYY-MM-DD',
                      ranges: {
                        今日: [moment(), moment()],
                        本月: [moment().startOf('month'), moment().endOf('month')],
                        上月: [
                          moment().startOf('month').subtract(1, 'months'),
                          moment().endOf('month').subtract(1, 'months'),
                        ],
                        最近7天: [moment().subtract(6, 'days'), moment()],
                        最近60天: [moment().subtract(59, 'days'), moment()],
                        最近90天: [moment().subtract(89, 'days'), moment()],
                      },
                    }}
                  />
                </LightFilter>
              ),
              search: {
                onChange: (e) => {
                  setQueryParamState({ ...queryParam, articleName: e.target.value });
                },
                onSearch: (value: string) => {
                  actionRef.current?.reset();
                },
              },
              // menu: {
              //     type: 'tab',
              //     activeKey: tabActiveKey,
              //     items: [
              //         {
              //             label: <span>选题线索{renderBadge(0, tabActiveKey === 'TableSubmitTopic')}</span>,
              //             key: 'TableTopicRender',
              //         },
              //         {
              //             label: <span>主动报送{renderBadge(0, tabActiveKey === 'TableSubmitActive')}</span>,
              //             key: 'TableTopicManage',
              //         },
              //     ],
              //     onChange: (key) => {
              //         setTabActiveKeyState(key as string)
              //     }
              // }
            }}
          />
        ) : (
          <TableSubmit isEditable={true} />
        )}
      </PageContainer>
    </DrawerForm>
  );
};
export default SubmitPool;
